<script lang="ts" setup>
import type { ReceiptRecordRefund } from '@/api/types/finance'
import { ref } from 'vue'
import { useRoute } from 'vue-router'
import { api } from '@/api'
import ApprovalActionBar from '@/components/ApprovalActionBar.vue'
import useBoolean from '@/hooks/useBoolean'
import { useFlow } from '@/hooks/useFlow'

definePage({
  style: {
    navigationBarTitleText: '资金退款详情',
  },
})

const route = useRoute()
const { currentProcess, getProcessInstance, getCurrentUserPendingTaskId } = useFlow()
const loading = useBoolean(true)
const refundDetail = ref<ReceiptRecordRefund | null>(null)
const errorMsg = ref('')
const flowIdValue = ref('')
const idValue = ref('')

// 格式化日期
function formatDate(dateStr?: string) {
  if (!dateStr)
    return '-'
  const date = new Date(dateStr)
  if (Number.isNaN(date.getTime()))
    return dateStr

  // 获取各个时间组件
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hour = String(date.getHours()).padStart(2, '0')
  const minute = String(date.getMinutes()).padStart(2, '0')
  const second = String(date.getSeconds()).padStart(2, '0')

  // 返回 "YYYY-MM-DD HH:mm:ss" 格式
  return `${year}-${month}-${day} ${hour}:${minute}:${second}`
}

// 格式化金额
function formatAmount(amount?: number) {
  if (amount === undefined || amount === null)
    return '0.00'
  return amount.toFixed(2)
}

// 获取退款详情
async function fetchRefundDetail() {
  loading.setTrue()
  errorMsg.value = ''
  try {
    await getProcessInstance(idValue.value)
    // 获取当前用户待审批任务ID
    const taskId = await getCurrentUserPendingTaskId(idValue.value)
    if (taskId) {
      flowIdValue.value = taskId
    }

    const id = route.params.id as string
    if (!id) {
      errorMsg.value = '参数错误'
      loading.setFalse()
      return
    }

    // 获取退款详情
    const [refundRes] = await Promise.all([
      api.finance.getReceiptRecordRefundById(id),
    ])

    refundDetail.value = refundRes.data || null
  }
  catch (error) {
    errorMsg.value = '获取数据失败'
    console.error('获取退款详情失败:', error)
  }
  finally {
    loading.setFalse()
  }
}

// 处理审批操作后的回调
async function handleActionChange() {
  // 延迟刷新以确保数据更新
  setTimeout(() => {
    fetchRefundDetail()
  }, 500)
}

onLoad((e: any) => {
  if (e.flowId) {
    flowIdValue.value = e.flowId
  }
  idValue.value = e.id || ''
  fetchRefundDetail()
})
</script>

<template>
  <view class="page">
    <!-- 审批状态卡片 -->
    <ApprovalStatusCard :current-process="currentProcess" :id-value="idValue" />
    <!-- 加载状态 -->
    <view v-if="loading.bool.value" class="loading-container">
      <text>加载中...</text>
    </view>

    <!-- 错误状态 -->
    <view v-else-if="errorMsg" class="error-container">
      <text class="error-text">{{ errorMsg }}</text>
      <button class="retry-btn" @click="fetchRefundDetail">
        重试
      </button>
    </view>

    <!-- 详情内容 -->
    <view v-else-if="refundDetail" class="content">
      <!-- 退款基本信息卡片 -->
      <view class="card">
        <view class="card-title">
          退款基本信息
        </view>
        <view class="card-content">
          <view class="info-row">
            <view class="info-label">
              退款单号
            </view>
            <view class="info-value">
              {{ refundDetail.refundNo || '-' }}
            </view>
          </view>
          <view class="info-row">
            <view class="info-label">
              退款金额
            </view>
            <view class="info-value amount">
              {{ formatAmount(refundDetail.amount) }}
            </view>
          </view>
          <view class="info-row">
            <view class="info-label">
              退款类型
            </view>
            <view class="info-value">
              {{ refundDetail.refundType || '-' }}
            </view>
          </view>
          <view class="info-row">
            <view class="info-label">
              退款原因
            </view>
            <view class="info-value">
              {{ refundDetail.reason || '-' }}
            </view>
          </view>
          <view class="info-row">
            <view class="info-label">
              申请时间
            </view>
            <view class="info-value">
              {{ formatDate(refundDetail.applyTime) }}
            </view>
          </view>
          <view class="info-row">
            <view class="info-label">
              退款时间
            </view>
            <view class="info-value">
              {{ formatDate(refundDetail.refundTime) }}
            </view>
          </view>
          <view class="info-row">
            <view class="info-label">
              状态
            </view>
            <view class="info-value">
              {{ refundDetail.status || '-' }}
            </view>
          </view>
          <view class="info-row">
            <view class="info-label">
              审批状态
            </view>
            <view class="info-value">
              {{ refundDetail.auditStatus || '-' }}
            </view>
          </view>
        </view>
      </view>

      <!-- 退款账户信息卡片 -->
      <view class="card">
        <view class="card-title">
          退款账户信息
        </view>
        <view class="card-content">
          <view class="info-row">
            <view class="info-label">
              收款人姓名
            </view>
            <view class="info-value">
              {{ refundDetail.payeeName || '-' }}
            </view>
          </view>
          <view class="info-row">
            <view class="info-label">
              退款账号
            </view>
            <view class="info-value">
              {{ refundDetail.accountNo || '-' }}
            </view>
          </view>
          <view class="info-row">
            <view class="info-label">
              开户行
            </view>
            <view class="info-value">
              {{ refundDetail.bankName || '-' }}
            </view>
          </view>
        </view>
      </view>

      <!-- 关联业务信息卡片 -->
      <view class="card">
        <view class="card-title">
          关联业务信息
        </view>
        <view class="card-content">
          <view class="info-row">
            <view class="info-label">
              关联业务ID
            </view>
            <view class="info-value">
              {{ refundDetail.businessId || '-' }}
            </view>
          </view>
        </view>
      </view>

      <!-- 退款凭证信息卡片 -->
      <view v-if="refundDetail.refundProofInfo" class="card">
        <view class="card-title">
          退款凭证信息
        </view>
        <view class="card-content">
          <view class="info-row">
            <view class="info-label">
              凭证详情
            </view>
            <view class="info-value">
              {{ JSON.stringify(refundDetail.refundProofInfo) || '-' }}
            </view>
          </view>
        </view>
      </view>

      <!-- 备注信息卡片 -->
      <view v-if="refundDetail.remark" class="card">
        <view class="card-title">
          备注信息
        </view>
        <view class="card-content">
          <view class="info-row">
            <view class="info-label">
              备注
            </view>
            <view class="info-value">
              {{ refundDetail.remark }}
            </view>
          </view>
        </view>
      </view>

      <!-- 审批操作栏 -->
      <ApprovalActionBar
        v-if="flowIdValue && currentProcess?.status === 1"
        :process-id="flowIdValue"
      />
    </view>

    <!-- 无数据状态 -->
    <view v-else class="empty-container">
      <text class="empty-text">暂无数据</text>
    </view>
  </view>
</template>

<style lang="scss" scoped>
.page {
  padding: 20rpx;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.loading-container,
.error-container,
.empty-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60rpx 0;
}

.error-text {
  color: #e64340;
  margin-bottom: 20rpx;
}

.retry-btn {
  margin-top: 20rpx;
}

.content {
  display: flex;
  flex-direction: column;
  gap: 20rpx;
}

.card {
  background-color: #fff;
  border-radius: 12rpx;
  padding: 24rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.card-title {
  font-size: 32rpx;
  font-weight: 600;
  color: #333;
  margin-bottom: 20rpx;
  padding-bottom: 16rpx;
  border-bottom: 1rpx solid #f0f0f0;
}

.card-content {
  display: flex;
  flex-direction: column;
  gap: 16rpx;
}

.info-row {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  padding: 8rpx 0;
}

.info-label {
  font-size: 28rpx;
  color: #666;
  flex: 1;
}

.info-value {
  font-size: 28rpx;
  color: #333;
  flex: 2;
  text-align: right;
  word-break: break-all;
}

.info-value.amount {
  font-size: 36rpx;
  font-weight: 600;
  color: #e64340;
}
</style>
